package cn.kgc.springmvc02.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author: mosin
 * @version: v1.0  2022/12/13
 * springmvc中拦截器的使用
 */
public class LoginInterceptor implements HandlerInterceptor {

    //请求之前调用该方法   boolean  true  放行  false 拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("-----------preHandle----------");
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute("user");

        if(attribute!=null){
            return true;
        }

        // 没有登录 重定向到登录页
        response.sendRedirect(request.getContextPath()+"/login.jsp");
        return false;
    }

    // 请求完成后调用该方法
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("-----------postHandle----------");
    }

    // 视图渲染完成之后
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("-----------afterCompletion----------");
    }
}
